import pandas as pd
import geopandas as gpd
import datetime
from shapely import wkt
from shapely.geometry import MultiPolygon, Polygon

# Define the input and output file paths
fn = r'G:\2024工作\衢州\金华隐患点.xlsx'
out_fn = r"G:\2024工作\衢州\result_{}.gdb".format(datetime.datetime.now().strftime('%Y%m%d'))

# Function to ensure all geometries are MultiPolygon
def ensure_multipolygon(geometry):
    if isinstance(geometry, Polygon):
        return MultiPolygon([geometry])
    return geometry

# Using with statement to open the Excel file
with pd.ExcelFile(fn) as xls:
    # Read the Excel file into a DataFrame
    df = pd.read_excel(xls)
    
    # Convert 'WKT' column to geometries
    df['geometry'] = df['WKT'].apply(wkt.loads)
    
    # Convert all geometries to MultiPolygon
    df['geometry'] = df['geometry'].apply(ensure_multipolygon)
    
    # Create a GeoDataFrame
    gdf = gpd.GeoDataFrame(df, geometry='geometry', crs="EPSG:4490")
    
    # Check for and filter out invalid geometries
    valid_gdf = gdf[gdf.is_valid]
    
    # Print out any invalid geometries if present
    invalid_geometries = gdf[~gdf.is_valid]
    if not invalid_geometries.empty:
        print("Invalid geometries detected and removed:")
        print(invalid_geometries)
    
    # Write the valid GeoDataFrame to a File Geodatabase
    valid_gdf.to_file(out_fn, driver='OpenFileGDB', encoding='utf-8')

print("已输出完毕")
